# -*- coding: UTF-8 -*-

# profiles.py
#
#  Copyright (c) 2007 INdT (Instituto Nokia de Technologia)
#                2007 Kenneth Rohde Christiansen
#
#  Author: Kenneth Rohde Christiansen <kenneth.christiansen@gmail.com>
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License as
#  published by the Free Software Foundation; either version 2 of the
#  License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
#  USA

import os

class Profiles(object):


    def __init__(self):
        self.profiles = {}
        self.load_profiles()

    def load_profiles(self):
        path = "/usr/share/ereseva/profiles"

        def get_key_and_value(line):
            key, value = line.split("=")
            key = key.strip()
            value = value.strip()
            if value.endswith("\n"):
                value = value[:-1]

            return key, value

        if os.path.exists(path):
            files = os.walk(path).next()[2]

            for filename in files:

                if not filename.endswith(".profile"):
                    continue

                profile_file = open(path + "/" + filename, 'r')

                profile_name = filename.split(".")[0]

                self.profiles[profile_name] = {}
                self.profiles[profile_name]["Name"] = None
                self.profiles[profile_name]["Description"] = None
                self.profiles[profile_name]["Manager"] = None
                self.profiles[profile_name]["Protocol"] = None
                self.profiles[profile_name]["Icon"] = None
                self.profiles[profile_name]["Params"] = {}

                lines = profile_file.readlines()

                if not lines[0].startswith("[Profile]"):
                    continue

                for line in lines[1:]:
                    key, value = get_key_and_value(line)

                    # parameter
                    if key.startswith("Default"):
                        length = len("Default-")
                        key = key[length:]

                        if value.endswith("hidden"):
                            length = len(" hidden")
                            value = value[:- length]
                            hide = True
                        else:
                            hide = False

                        self.profiles[profile_name]["Params"][key] = (None, value, hide)
                    else:
                        if key.startswith("_"):
                            key = key[1:]

                        self.profiles[profile_name][key] = value

                manager = self.profiles[profile_name]["Manager"]

                if manager != None:
                    manager_path = "/usr/share/telepathy/managers/" + manager + ".manager"

                    if os.path.exists(manager_path):
                        manager_file = open(manager_path, 'r')

                        lines = manager_file.readlines()

                        read = False

                        for line in lines:
                            if line.startswith("[Protocol"):
                                read = True
                                continue

                            if read == False:
                                continue

                            key, value = get_key_and_value(line)

                            if key.startswith("param-"):
                                key = key[6:]
                                type = value.split(" ")[0].strip()

                                do_update = False

                                if "required" in value.split(" "):
                                    do_update = True

                                try:
                                    unused, default_value, hide = self.profiles[profile_name]["Params"][key]
                                    do_update = True
                                except KeyError:
                                    default_value = None
                                    hide = False

                                if do_update:
                                    if type == "s":
                                        type = "string"
                                    elif type == "n":
                                        type = "int"
                                    elif type == "b":
                                        type = "boolean"
                                    elif type == "q":
                                        type = "uint"
                                    else:
                                        type = "unknown"

                                    self.profiles[profile_name]["Params"][key] = (type, default_value, hide)


    def get_profile_name(self, profile):
        return self.profiles[profile]["Name"]


    def get_profile_description(self, profile):
        return self.profiles[profile]["Description"]


    def get_profile_protocol(self, profile):
        return self.profiles[profile]["Protocol"]


    def get_profile_manager(self, profile):
        return self.profiles[profile]["Manager"]


    def get_profile_parameters(self, profile):
        return self.profiles[profile]["Params"]

    def get_profile_ids(self):
        profiles = []

        for profile in self.profiles.keys():
            profiles.append(profile)

        return profiles

if __name__ == "__main__":
    profile = Profiles()

    print profile.get_profile_ids()
    print profile.get_profile_parameters('google-talk')

    for profile_id in profile.get_profile_ids():
        print "Profile name:\t\t %s" % profile.get_profile_name(profile_id)
        print "Profile description:\t %s" % profile.get_profile_description(profile_id)

        print "Protocol:\t\t %s (via %s)" % (profile.get_profile_protocol(profile_id), \
            profile.get_profile_manager(profile_id))

        print "Parameters:\n"

        params = profile.get_profile_parameters(profile_id)
        for param in params:
            type, value, hidden = params[param]
            print "\tParameter: %s, type: %s, value: '%s', hidden: %s" % (param, type, value, hidden)

        print "\n"\

